package com.webvihar.access2db.activities;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.webvihar.access2db.R;
import com.webvihar.access2db.asynctasks.A2DbAsyncWebRequestTask;
import com.webvihar.access2db.builders.RunQueryBuilder;
import com.webvihar.access2db.components.CustomEditText;
import com.webvihar.access2db.model.Header;
import com.webvihar.access2db.model.QueryResult;
import com.webvihar.access2db.model.TableDataItem;
import com.webvihar.access2db.model.TableRowItem;
import com.webvihar.access2db.restapi.A2DbRunQueryRequest;
import com.webvihar.access2db.restapi.A2DbWebResult;
import com.webvihar.access2db.utils.PreferencesManager;
import com.webvihar.common.utils.Logger;

public class TableDataOperationActivity extends BaseActivity implements OnClickListener{

	private LinearLayout dynamicLL;
	private Button addButton; 
	private Button editButton; 
	private Button deleteButton;
	private TextView titleTxt;
	private ImageButton titleAddBtn;
	private List<View> fields;
	
	private TableRowItem oldRowItem;
	private TableRowItem newRowItem;
	
	/** Called when the activity is first created. */
	@SuppressWarnings("unchecked")
	@Override 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
		setContentView(R.layout.table_data_operation);
		initUI();
		setTitleBar();
		setListeners();
		setMode();
		
		if(tableRow != null) {
			oldRowItem = (TableRowItem)tableRow;
			newRowItem = getCopy(oldRowItem);//(TableRowItem)tableRow;
			addFields(oldRowItem);
		} else {
			addFieldsToInserData((List<Header>) tableHeaders);
		}
	}

	private void setMode() {
		Bundle bundle = getIntent().getExtras();
		String mode = bundle.getString(KEY_TABLE_DATA_NAVIGATION_MODE);
		if(mode.equalsIgnoreCase(TableDataActivity.TABLE_DATA_OPERATION_TYPE_ADD)) {
			// hide edit and delete buttons
			hideView(addButton, false);
			hideView(editButton, true);
			hideView(deleteButton, true);
		} else if(mode.equalsIgnoreCase(TableDataActivity.TABLE_DATA_OPERATION_TYPE_EDIT_DELETE)) {
			// hide add button
			hideView(addButton, true);
			hideView(editButton, false);
			hideView(deleteButton, false);
		}
	}

	private void setTitleBar() {
		titleTxt = (TextView) findViewById(R.id.title_txt);
		titleTxt.setText(getString(R.string.tables_data_txt));
		titleAddBtn = (ImageButton) findViewById(R.id.title_action_image_btn);
		titleAddBtn.setVisibility(View.GONE);
	}

	private TableRowItem getCopy(TableRowItem oldRowItem) {
		TableRowItem rowItem = new TableRowItem();
		List<TableDataItem> items = new ArrayList<TableDataItem>();
		for(int i=0; i<oldRowItem.items.size(); i++) {
			TableDataItem item = new TableDataItem();
			item.header = oldRowItem.items.get(i).header;
			item.data = oldRowItem.items.get(i).data;
			items.add(item);
		}
		rowItem.items = items;
		return rowItem;
	}

	private void addFields(TableRowItem rowItem) {
		List<TableDataItem> items = rowItem.items;
		fields = new ArrayList<View>();
		for(int i=0;i<items.size(); i++) {
			TableDataItem item = items.get(i);
			View fieldView = getFieldView(item.header.type, item);
			if(i == 0) {
				fieldView.requestFocus();
			} else {
				fieldView.clearFocus();
			}
			dynamicLL.addView(fieldView);
			fields.add(fieldView);
		}
	}

	private void addFieldsToInserData(List<Header> headers) {
		fields = new ArrayList<View>();
		for(int i=0; i<headers.size(); i++) {
			Header header = headers.get(i);
			View fieldView = getFieldView(header);
			if(i == 0) {
				fieldView.requestFocus();
			} else {
				fieldView.clearFocus();
			}
			dynamicLL.addView(fieldView);
			fields.add(fieldView);
		}
	}
	
	private void initUI() {
		dynamicLL = (LinearLayout)findViewById(R.id.table_data_operation_dynamic_linear_layout);
		addButton = (Button)findViewById(R.id.table_data_operation_add_btn);
		editButton = (Button)findViewById(R.id.table_data_operation_edit_btn);
		deleteButton = (Button)findViewById(R.id.table_data_operation_delete_btn);
	}

	private void setListeners() {
		addButton.setOnClickListener(this);
		editButton.setOnClickListener(this);
		deleteButton.setOnClickListener(this); 
	}

	private View getFieldView(String type, TableDataItem item) {
		CustomEditText et = new CustomEditText(this);
		et.setTitleText(item.header.title+"("+type     +")");
		et.setDataText(item.data);
		return et;
	}

	private View getFieldView(Header header) {
		CustomEditText et = new CustomEditText(this);
		et.setTitleText(header.title+"("+header.type+")");
		et.setDataText(null);
		return et;
	}
	
	@SuppressWarnings("unchecked")
	private void displayUpdatedData() {
		if(addButton.isShown()) {
			newRowItem = new TableRowItem();
			newRowItem.items = new ArrayList<TableDataItem>();
			List<Header> headers = (List<Header>) tableHeaders;
			for(int i=0; i<headers.size(); i++) {
				CustomEditText et = (CustomEditText)fields.get(i);
				TableDataItem dataItem = new TableDataItem();
				dataItem.header = headers.get(i);
				dataItem.data = et.getDataText();
				newRowItem.items.add(dataItem);
			}
		} else {
			for(int i=0; i<newRowItem.items.size(); i++) {
				CustomEditText et = (CustomEditText)fields.get(i);
				newRowItem.items.get(i).data = et.getDataText();
			}
		}
	}

	private void insertDataRequest() {
		String insertQuery = getQueryBuilder().getInsertTableDataQuery(PreferencesManager.getString(this, PREF_SESSION_TABLE_NAME), newRowItem);
		executeTableQuery(insertQuery);
	}
	
	private void updateDataRequest() {
		String updateQuery = getQueryBuilder().getUpdateTableDataQuery(PreferencesManager.getString(this, PREF_SESSION_TABLE_NAME), oldRowItem, newRowItem);
		executeTableQuery(updateQuery);
	}

	private void deleteDataRequest() {
		String deleteQuery = getQueryBuilder().getDeleteTableDataQuery(PreferencesManager.getString(this, PREF_SESSION_TABLE_NAME), oldRowItem);
		Logger.logInfo(Logger.LOG_TAG, deleteQuery);
		executeTableQuery(deleteQuery);
	}

	@Override
	public void onClick(View v) {
		
		if(v == addButton) {
			displayUpdatedData();
			insertDataRequest();
		} else if(v == editButton) {
			displayUpdatedData();
			updateDataRequest();
		} else if (v == deleteButton) {
			displayUpdatedData();
			deleteDataRequest();
		}
	}
	private void executeTableQuery(String query) {
		A2DbRunQueryRequest request = new A2DbRunQueryRequest();
		request.encoded = true;
		request.host = 	PreferencesManager.getString(getApplicationContext(), PREF_SESSION_HOST);
		request.port =  PreferencesManager.getString(getApplicationContext(), PREF_SESSION_PORT);
		request.username = PreferencesManager.getString(getApplicationContext(), PREF_SESSION_USERNAME);
		request.password = PreferencesManager.getString(getApplicationContext(), PREF_SESSION_PASSWORD);
		request.dbname = PreferencesManager.getString(getApplicationContext(), PREF_SESSION_DBNAME);
		request.query = query;
		request.requestDelegate = new RunQueryBuilder();
		new A2DbAsyncWebRequestTask(true, getApplicationContext(), runQueryRequestHandler, getProgressDialog()).execute(request);
	}

	private Handler runQueryRequestHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			@SuppressWarnings("unchecked")
			A2DbWebResult<QueryResult> response = (A2DbWebResult<QueryResult>) msg.obj;
			if(response == null) {
				showToast("Response is null");
				TableDataOperationActivity.this.finish();
			} else if(response.entity == null) {
				showToast("Server not found...");
				TableDataOperationActivity.this.finish();
			} else if(response.entity.result == null){
				showToast(response.entity.error+"");
				TableDataOperationActivity.this.finish();
			} else {
				showToast(response.entity.result + "");
				TableDataOperationActivity.this.finish();
			}
		}
	};

}
